package com.hjq.demo.ui.fragment;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.widget.Button;

import com.hjq.base.BaseDialog;
import com.hjq.base.action.HandlerAction;
import com.hjq.demo.R;
import com.hjq.demo.aop.SingleClick;
import com.hjq.demo.app.TitleBarFragment;
import com.hjq.demo.ui.activity.HomeActivity;
import com.hjq.demo.ui.adapter.TabAdapter;
import com.hjq.demo.ui.dialog.MessageDialog;
import com.hjq.demo.ui.dialog.TipsDialog;
import com.hjq.demo.ui.dialog.WaitDialog;
import com.hjq.demo.ui.helpers.MessageEvent;
import com.hjq.demo.ui.helpers.MySocketClientManager;
import com.hjq.demo.widget.XCollapsingToolbarLayout;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

/**
 * author : Android 轮子哥
 * github : https://github.com/getActivity/AndroidProject
 * time   : 2018/10/18
 * desc   : 首页 Fragment
 */
public final class HomeFragment1 extends TitleBarFragment<HomeActivity>
        implements HandlerAction, TabAdapter.OnTabListener, ViewPager.OnPageChangeListener,
        XCollapsingToolbarLayout.OnScrimsListener {

    private Button mCommitView;

    public static HomeFragment1 newInstance() {
        return new HomeFragment1();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.home_fragment_1;
    }


    @Override
    protected void initView() {
        mCommitView = findViewById(R.id.my_btn_all_close_open);
        if (mWaitDialog == null) {
            mWaitDialog = new WaitDialog.Builder(this.getAttachActivity())
                    // 消息文本可以不用填写
                    .setMessage("执行中...")
                    .create();
        }
        setOnClickListener(R.id.my_btn_tab_light_status, R.id.my_btn_tab_tv_status,
                R.id.my_btn_tab_device_status, R.id.my_btn_all_close_open,R.id.my_btn_all_close,R.id.my_btn_all_open,
                R.id.my_btn_switch_light_1, R.id.my_btn_switch_light_2, R.id.my_btn_switch_light_3);
    }

    @SingleClick
    @Override
    public void onClick(View view) {
        int viewId = view.getId();
        if (viewId == R.id.my_btn_tab_light_status) {
            HomeActivity.mViewPager.setCurrentItem(1);
        } else if (viewId == R.id.my_btn_tab_tv_status) {
            HomeActivity.mViewPager.setCurrentItem(2);
        } else if (viewId == R.id.my_btn_tab_device_status) {
            HomeActivity.mViewPager.setCurrentItem(3);
        } else if (viewId == R.id.my_btn_all_close) {
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(0,"G");
                    EventBus.getDefault().post(new MessageEvent(1, 0, false));
                }
            }).start();
        }else if (viewId == R.id.my_btn_all_open) {
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(0,"K");
                    EventBus.getDefault().post(new MessageEvent(1, 0, true));
                }
            }).start();
        }else if (viewId == R.id.my_btn_all_close_open) {
//            mCommitView.showProgress();
            if (!mWaitDialog.isShowing()) {
                mWaitDialog.show();
            }
            new Thread(new Runnable() {
                @Override
                public void run() {
                    boolean open = MySocketClientManager.getInstance().turnStatusAll(0);
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(0, open ? "G" : "K");
                    if (turnResult == false) {
                        EventBus.getDefault().post(new MessageEvent(1, -1, turnResult));
                        return;
                    }
                    open = !open;//执行后状态反转
                    EventBus.getDefault().post(new MessageEvent(1, 0, open));
                }
            }).start();
        } else if (viewId == R.id.my_btn_switch_light_1) {
            post(new Runnable() {
                @Override
                public void run() {
                    boolean open = MySocketClientManager.getInstance().turnStatusAll(1);
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(1, open ? "G" : "K");
                    if (turnResult == false) {
                        return;
                    }
                    open = !open;//执行后状态反转
                    Button button = findViewById(viewId);
                    button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
                }
            });
        } else if (viewId == R.id.my_btn_switch_light_2) {
            post(new Runnable() {
                @Override
                public void run() {
                    boolean open = MySocketClientManager.getInstance().turnStatusAll(2);
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(2, open ? "G" : "K");
                    if (turnResult == false) {
                        return;
                    }
                    open = !open;//执行后状态反转
                    Button button = findViewById(viewId);
                    button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
                }
            });
        } else if (viewId == R.id.my_btn_switch_light_3) {
            post(new Runnable() {
                @Override
                public void run() {
                    boolean open = MySocketClientManager.getInstance().turnStatusAll(3);
                    boolean turnResult = MySocketClientManager.getInstance().turnAll(3, open ? "G" : "K");
                    if (turnResult == false) {
                        return;
                    }
                    open = !open;//执行后状态反转
                    Button button = findViewById(viewId);
                    button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
                }
            });
        }
    }

    /**
     * 等待对话框
     */
    private BaseDialog mWaitDialog;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEvent event) {
        // Do something
        if (event == null) return;
        if (event.getPage() != 1) return;
        int type = event.getType();
        boolean open = event.isOpen();
        Button button = null;
        try {
            if (type == -1) {
//            mCommitView.showSucceed();
                mWaitDialog.dismiss();
                return;
            }
            if (type == 0) {
//            mCommitView.showSucceed();
//            button = findViewById(R.id.my_btn_all_close_open);
                mCommitView.setBackground(ContextCompat.getDrawable(getContext(), open ? R.mipmap.all_close : R.mipmap.all_open));
                switchAll(open);
                mWaitDialog.dismiss();
            } else if (type == 1) {
                button = findViewById(R.id.my_btn_switch_light_1);
                button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
            } else if (type == 2) {
                button = findViewById(R.id.my_btn_switch_light_2);
                button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));

            } else if (type == 3) {
                button = findViewById(R.id.my_btn_switch_light_3);
                button.setBackground(ContextCompat.getDrawable(getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
            }
        } catch (Exception e) {
            showError(getContext(), e.getMessage());
        }
    }

    public static void showError(Context c, String msg){
        new TipsDialog.Builder(c)
                .setIcon(TipsDialog.ICON_ERROR)
                .setMessage(msg)
                .show();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    public boolean switchAll(boolean open) {
        Button button1 = this.findViewById(R.id.my_btn_switch_light_1);
        Button button2 = this.findViewById(R.id.my_btn_switch_light_2);
        Button button3 = this.findViewById(R.id.my_btn_switch_light_3);
        button1.setBackground(ContextCompat.getDrawable(this.getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
        button2.setBackground(ContextCompat.getDrawable(this.getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
        button3.setBackground(ContextCompat.getDrawable(this.getContext(), !open ? R.mipmap.my_switch_close : R.mipmap.my_switch_open));
        return true;
    }

    @Override
    protected void onFragmentResume(boolean first) {
        super.onFragmentResume(first);

        new Thread(new Runnable() {
            @Override
            public void run() {
                boolean open = MySocketClientManager.getInstance().turnStatusAll(0);
                EventBus.getDefault().post(new MessageEvent(1, 0, open));

                open = MySocketClientManager.getInstance().turnStatusAll(1);
                EventBus.getDefault().post(new MessageEvent(1, 1, open));

                open = MySocketClientManager.getInstance().turnStatusAll(2);
                EventBus.getDefault().post(new MessageEvent(1, 2, open));

                open = MySocketClientManager.getInstance().turnStatusAll(3);
                EventBus.getDefault().post(new MessageEvent(1, 3, open));
            }
        }).start();
    }


    @Override
    protected void initData() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                MySocketClientManager.getInstance().connectAll();
            }
        }).start();
    }

    @Override
    public boolean isStatusBarEnabled() {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled();
    }

    /**
     * {@link TabAdapter.OnTabListener}
     */

    @Override
    public boolean onTabSelected(RecyclerView recyclerView, int position) {
        return true;
    }

    /**
     * {@link ViewPager.OnPageChangeListener}
     */

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
    }

    @Override
    public void onPageSelected(int position) {
    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    /**
     * CollapsingToolbarLayout 渐变回调
     * <p>
     * {@link XCollapsingToolbarLayout.OnScrimsListener}
     */
    @SuppressLint("RestrictedApi")
    @Override
    public void onScrimsStateChange(XCollapsingToolbarLayout layout, boolean shown) {
        getStatusBarConfig().statusBarDarkFont(shown).init();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

}